library(dplyr)
library(ggplot2)
library(tidyr)

model_estimates<-read.csv("estimates/gaymarriage_dyn_psraking8k_dgirtout.csv")
model_estimates<-subset(model_estimates, year==2000 | year==2016)
model_estimates<-select(model_estimates, abb, year, value_mean )
model_estimates<-spread(model_estimates, year, value_mean)
colnames(model_estimates)<-c("abb", "median_2000", "median_2016")

model_estimates2<-read.csv("estimates/gaymarriage_dyn_psraking8k_dgirtout.csv")
model_estimates2<-subset(model_estimates2, year==2000 | year==2016)
model_estimates2<-select(model_estimates2, abb, year, value_sd)
model_estimates2<-spread(model_estimates2, year, value_sd)
colnames(model_estimates2)<-c("abb", "sd_2000", "sd_2016")

model_estimates<-merge(model_estimates2, model_estimates, all.x=T, all.y=T)
data.graph<-model_estimates[order(model_estimates$median_2016),]
left.label<-as.vector(data.graph$abb)

pdf(paste("figures/ssm_change_overtime.pdf",sep=""),width=7.5, height=8.5)
 par(mfrow=c(1,1),mar=c(3,6,3,8))
#right.label<-paste("(", round(data.graph$median*100,0), "%)", sep="")
y.axis<-c(1: dim(data.graph)[1])
plot(data.graph$median_2016*100, y.axis, axes=F, xlim=c(0,100),ylim=c(.1,dim(data.graph)[1]),pch=19,main="",xlab='',ylab='',type="n")
for (i in 1: dim(data.graph)[1]){
	 segments(0, i, 100, i, col="grey")
}
segments(0,0,0,(dim(data.graph)[1]), col="light grey")
segments(50, 0, 50, (dim(data.graph)[1]), col="light grey")

segments((data.graph$median_2016-1.96*data.graph$sd_2016)*100, y.axis, (data.graph$median_2016+1.96*data.graph$sd_2016)*100, y.axis, col="blue",lwd=2)
segments((data.graph$median_2000-1.96*data.graph$sd_2000)*100, y.axis, (data.graph$median_2000+1.96*data.graph$sd_2000)*100, y.axis, col="red",lwd=2)
points(data.graph$median_2000*100, y.axis, col="red", pch=19, cex=.75)
points(data.graph$median_2016*100, y.axis, col="blue", pch=19, cex=.75)
axis(1,  pos=0,cex.axis=.8,at = seq(0,100,10))
axis(2, at = c(0,y.axis, (dim(data.graph)[1]+2)), label = c('',left.label,''), las = 1, cex.axis = 1, mgp =
c(2,1,0), pos=0,cex.axis=.5, tick=FALSE)
axis(4,at = c(0,y.axis, (dim(data.graph)[1]+2)), pos=100,label = c('',right.label,''), tick=FALSE,las = 2,cex.axis=.75, font=1)
title(main="Support for Same-Sex Marriage by State",xlab = "", ylab = "", cex.lab=1)
title(xlab = "Percentage of Public that Supports Same-Sex Marriage",cex.lab=1, line=1)
dev.off()

